import fs from 'fs';
import { dialog } from 'electron';
import { PDFDocument } from 'pdf-lib';
import QRCode from 'qrcode';

export async function addQRCodeToPdf({ filePath, qrText, qrPositions = [] }) {
  try {
    const buffer = fs.readFileSync(filePath);
    const pdfDoc = await PDFDocument.load(buffer);
    
    // 生成二维码
    const qrBuffer = await QRCode.toBuffer(qrText, {
      width: 200,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    });
    
    const qrImage = await pdfDoc.embedPng(qrBuffer);
    const pages = pdfDoc.getPages();
    
    // 如果没有指定位置，默认在每页中间正上方
    if (qrPositions.length === 0) {
      for (let i = 0; i < pages.length; i++) {
        const page = pages[i];
        const { width, height } = page.getSize();
        
        // 默认位置：中间正上方，距离顶部50px
        const qrWidth = 100;
        const qrHeight = 100;
        const x = (width - qrWidth) / 2;
        const y = height - qrHeight - 50;
        
        page.drawImage(qrImage, {
          x,
          y,
          width: qrWidth,
          height: qrHeight
        });
      }
    } else {
      // 使用用户指定的位置
      qrPositions.forEach(({ pageIndex, x, y, width, height }) => {
        if (pageIndex < pages.length) {
          const page = pages[pageIndex];
          page.drawImage(qrImage, {
            x,
            y,
            width: Math.max(width, 60), // 最小60px
            height: Math.max(height, 60)
          });
        }
      });
    }
    
    const pdfBytes = await pdfDoc.save();
    return pdfBytes;
  } catch (error) {
    console.error('Error adding QR code to PDF:', error);
    throw error;
  }
}

export async function selectSaveDirectory() {
  const result = await dialog.showOpenDialog({
    properties: ['openDirectory'],
    title: '选择保存目录'
  });
  
  if (!result.canceled && result.filePaths.length > 0) {
    return result.filePaths[0];
  }
  return null;
}